//
//  ShowDiaryViewController.m
//  PipeNote
//
//  Created by lanou3g on 15/12/18.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "ShowDiaryViewController.h"
#import "DiaryViewController.h"
#import "JokeDataManager.h"
#import "AppDelegate.h"
#import "Write.h"
#import "PhotoDetailed.h"
@interface ShowDiaryViewController ()
{
    UIImageView *imageView;
    UIScrollView *scrollView;
    UITextView *textView;
    UIBarButtonItem *rightItem;
    UIBarButtonItem *saveItem;
    UIButton *homePageButton;
    UITextView *aTextView;
}

//用于手势识别
@property (nonatomic,assign) BOOL isTap;


@end

@implementation ShowDiaryViewController

- (void)dealloc{
    
    //控制器所有通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //移除动画
    [homePageButton.layer removeAnimationForKey:@"keyA3"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //背景图片
    [self background];
    

    //创建scrollView
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 150, ScreenFrame_Widdth, ScreenFrame_Height)];
  //  scrollView.contentSize = CGSizeMake(ScreenFrame_Widdth, ScreenFrame_Height*2);
    [self.view addSubview:scrollView];
    
    
    //创建textView
    [self textView];
     scrollView.contentSize = CGSizeMake(0,textView.frame.size.height+textView.frame.origin.y+180);
    
    //返回首页
    [self homePage];
   
    //编辑按钮
    [self editor];
    //手势
    [self gesture];
}

//返回首页
- (void)homePage{
    
    homePageButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 80, 60, 60)];
    [homePageButton setTitle:@"首页" forState:UIControlStateNormal];
    [homePageButton addTarget:self action:@selector(homePageItemAction) forControlEvents:UIControlEventTouchUpInside];
    homePageButton.font = [UIFont systemFontOfSize:25];
//    homePageButton.backgroundColor = [UIColor redColor];
    [self.view addSubview:homePageButton];
    
    //添加动画
    //计时器
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(animation) userInfo:nil repeats:YES];
}

//添加动画
- (void)animation{
    
    CAKeyframeAnimation *keyA3 = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    keyA3.duration = 1;
    id obj6 = @(0.5);
    id obj7 = @(1);
    id obj8 = @(0.5);
    keyA3.values = @[obj6,obj7,obj8];
    [homePageButton.layer addAnimation:keyA3 forKey:@"keyA3"];
}



//返回首页
- (void)homePageItemAction{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


//编辑按钮
- (void)editor{
    
    rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

//编辑按钮事件
- (void)rightItemAction:(UIBarButtonItem *)sender{
    
    rightItem.title = @"正在编辑";
   
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *playAlert1 = [UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        textView.userInteractionEnabled = YES;
        
        rightItem.title = @"保存";
        homePageButton.hidden = YES;
        
        //编辑后保存
        [self saveData];
        
        //删除旧的
        [self oldDelete];
        
        aTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, ScreenFrame_Widdth - 20, 200)];
        
        if (ScreenFrame_Height == 480) {
            aTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 80, ScreenFrame_Widdth - 20, 180)];
        }
        
        aTextView.backgroundColor = [UIColor clearColor];
        textView.hidden = YES;
        //让键盘自动弹出
        [aTextView becomeFirstResponder];
        aTextView.text = textView.text;
        aTextView.font = [UIFont boldSystemFontOfSize:18];
        [self.view addSubview:aTextView];
        
    }];
    
    UIAlertAction *playAlert2 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //删除
        [self delete];
        
    }];
    
    UIAlertAction *playAlert3 = [UIAlertAction actionWithTitle:@"全部删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        
        //提示是否全部删除
        [self allDeleteContent];
        
    }];
    
    
    UIAlertAction *playAlert4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        rightItem.title = @"编辑";
    }];
    
    [alertVC addAction:playAlert1];
    [alertVC addAction:playAlert2];
    [alertVC addAction:playAlert3];
    [alertVC addAction:playAlert4];
    [self presentViewController:alertVC animated:YES completion:nil];
}

 //提示是否全部删除
- (void)allDeleteContent{
    
    UIAlertController *alertVC1 = [UIAlertController alertControllerWithTitle:@"是否全部删除" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *allDeleteAlert = [UIAlertAction actionWithTitle:@"全部删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
       
        //全部删除
        [self allDelete];
    }];
    
    UIAlertAction *allDeleteAlert1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        rightItem.title = @"编辑";
    }];
    
    [alertVC1 addAction:allDeleteAlert];
    [alertVC1 addAction:allDeleteAlert1];
    [self presentViewController:alertVC1 animated:YES completion:nil];
}



//删除事件
- (void)delete{
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Write"];
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"content = %@",textView.text];
    request.predicate = cata;
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Write *write in array) {
        [app.managedObjectContext deleteObject:write];
    }
    
    if ([app.managedObjectContext hasChanges]) {
        [app.managedObjectContext save:nil];
    }


    [self dismissViewControllerAnimated:YES completion:nil];
}


//手势
- (void)gesture{
    //轻拍手势
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGRAction)];
    //设置点击次数
    tapGR.numberOfTapsRequired = 2;
    //设置手指个数
    tapGR.numberOfTouchesRequired = 2;
    //添加手势
    [self.view addGestureRecognizer:tapGR];
    
    //让isTap初值为NO
    self.isTap = NO;
}
//手势事件
- (void)tapGRAction{
    
    if (self.isTap == NO) {
        self.isTap = YES;
        textView.hidden = YES;
    }else{
        self.isTap = NO;
        textView.hidden = NO;
    }
    
}

//编辑后保存
- (void)saveData{
    
    //通知修改字数
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testing) name:UITextViewTextDidChangeNotification object:nil];
    
    saveItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveItemAction)];
    self.navigationItem.rightBarButtonItem = saveItem;
    
    saveItem.enabled = NO;
}

//通知修改字数
- (void)testing{
    
    if (aTextView.text.length >= 1) {
        
        saveItem.enabled = YES;
        
    }else{
        
        saveItem.enabled = NO;
    }
    
}



//编辑后保存事件
- (void)saveItemAction{
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    Write *write = [NSEntityDescription insertNewObjectForEntityForName:@"Write" inManagedObjectContext:app.managedObjectContext];
    write.content = aTextView.text;
    [app saveContext];
    

     [self dismissViewControllerAnimated:YES completion:nil];
}

//删除旧的
- (void)oldDelete{
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Write"];
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"content = %@",textView.text];
    request.predicate = cata;
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Write *write in array) {
        [app.managedObjectContext deleteObject:write];
    }
    
    if ([app.managedObjectContext hasChanges]) {
        [app.managedObjectContext save:nil];
    }

    
}

//全部删除
- (void)allDelete{
    
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Write"];
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"content != 0"];
    request.predicate = cata;
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Write *write in array) {
        [app.managedObjectContext deleteObject:write];
    }
    
    if ([app.managedObjectContext hasChanges]) {
        [app.managedObjectContext save:nil];
    }
  
     [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)textView{
    
    textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, ScreenFrame_Widdth - 20, ScreenFrame_Height - 10)];
    textView.backgroundColor = [UIColor clearColor];
    //设置字体大小
    textView.font = [UIFont boldSystemFontOfSize:20];
    //     textView.font = [UIFont fontWithName:@"FZYaSong-H-GBK" size:25];
    textView.userInteractionEnabled = NO;
    [scrollView addSubview:textView];
    
    //接收内容
    textView.text = self.content;
 //   自适应textView的高度
    CGFloat height = [self heightForLabelText:textView.text];
    CGRect rect = textView.frame;
    rect.size.height = height;
    textView.frame = rect;
    
}

//自适应高度方法
- (CGFloat)heightForLabelText:(NSString *)text{

    //size
    CGSize size = CGSizeMake(ScreenFrame_Widdth - 20, 10000);
    //attributes
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20]};

    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    //设置
    return rect.size.height + 60;
}


- (void)background{
    
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    imageView.frame = CGRectMake(0, 64, ScreenFrame_Widdth, ScreenFrame_Height);
    [self.view addSubview:imageView];
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    //创建搜索请求对象，并且指明所有的数据类型
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"PhotoDetailed"];
    NSArray *objcArray = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    PhotoDetailed *photo = objcArray.lastObject;
    
    UIImage *image = [UIImage imageWithData:photo.photo];
    imageView.image = image;
    
    if (objcArray.count == 0) {
        
        imageView.image = [UIImage imageNamed:@"日历背景1.jpeg"];
    }
    
    
}





@end
